const opn = require("opn");
const axios = require("axios");
const express = require("express");
const list = require("./data/data");

const headers = {
  accept: "application/json, text/plain, */*",
  "accept-language": "zh-CN,zh;q=0.9",
  "sec-ch-ua":
    '"Chromium";v="106", "Google Chrome";v="106", "Not;A=Brand";v="99"',
  "sec-ch-ua-mobile": "?0",
  "sec-ch-ua-platform": '"Windows"',
  "sec-fetch-dest": "empty",
  "sec-fetch-mode": "cors",
  "sec-fetch-site": "same-site",
  cookie:
    "buvid3=D5F38EEF-F4EB-8489-6B72-4D2BE7E6693694034infoc; b_nut=1667953494; CURRENT_FNVAL=4048; _uuid=DF10434B4-4EA8-DACB-2B84-C9C5CEA10666893500infoc; buvid_fp=f27b549fb4eeb5d82d73aee817f17e70; buvid4=FE799987-6A89-3C12-2757-E93D599E86DC96083-022110908-c8mC4VtaIp/pxFxY9St1Qw%3D%3D; b_lsid=D39B5CCE_1848F874E3E",
  Referer: "https://space.bilibili.com/477828976",
  "Referrer-Policy": "no-referrer-when-downgrade",
};

const app = express();
app.use(express.static("views"));
app.get("/data", async function (req, res) {
  try {
    const d = list.map(async (v) => {
      let id = v.url.match(/\d+/)[0];
      const result = await axios.get(
        `https://api.bilibili.com/x/space/arc/search?mid=${id}`,
        {
          headers,
        }
      );

      if (typeof result.data === "object") {
        return {
          count: result.data.data.page.count,
          url: v.url,
          name: v.name,
          videoList: result.data.data.list.vlist.map((vv) => ({
            title: vv.title,
            url: `https://www.bilibili.com/video/${vv.bvid}`,
            length: vv.length,
          })),
        };
      } else {
        return {
          count: 0,
          url: v.url,
          name: v.name,
          videoList: [],
        };
      }
    });
    const ress = await Promise.all(d);

    res.send({ msg: "查询成功", code: 0, data: ress });
  } catch (error) {
    res.send({ msg: "查询失败", code: 1, error });
  }
});

opn("http://127.0.0.1:8080/index.html");
app.listen(8080);
